package com.xf.tourismapp.fragments;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.DataSetObserver;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.fragment.app.ListFragment;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.xf.tourismapp.R;
import com.xf.tourismapp.activities.MainActivity;
import com.xf.tourismapp.entity.User;
import com.xf.tourismapp.model.ResultResponse;
import com.xf.tourismapp.util.HttpCallbackListener;
import com.xf.tourismapp.util.HttpUtil;
import com.xf.tourismapp.vo.PageVO;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;

public class HomePageFragment extends Fragment {


    private String originAddress = "http://2qmaev.natappfree.cc/student_manager/user/listUser";
    private static HomePageFragment homePageFragment;
    FragmentManager fragmentManager;
    MyFragmentList myFragmentList;
    MyButtonList myButtonList;
    TextView textViewArray[];
    String userArray[];
    PageVO pageVO;

    private HomePageFragment() {
    }

    public static synchronized HomePageFragment getHomePageFragmentInstance() {
        if (homePageFragment == null) {
            homePageFragment = new HomePageFragment();
        }
        return homePageFragment;
    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            // 获取到响应报文的数据
            String result = (String) msg.obj;
            // 转换成 ResultResponse
            ResultResponse resultResponse = JSONObject.parseObject(result, ResultResponse.class);
            // 继续转 PageVO
            pageVO = JSONObject.parseObject(JSONObject.toJSONString(resultResponse.getData()), PageVO.class);
            // 继续转成 List
            List<User> userList = JSONObject.parseArray(JSONObject.toJSONString(pageVO.getData()), User.class);
            userArray = new String[userList.size()];
            textViewArray = new TextView[userList.size()];
            for (int i = 0; i < userList.size(); i++) {
//                Log.e("datagrid", user.toString());
                userArray[i] = userList.get(i).getUsername();
                textViewArray[i] = new TextView(getActivity());
                ((TextView) textViewArray[i]).setText(userList.get(i).getUsername());
                ((TextView) textViewArray[i]).setTextSize(20);
                ((TextView) textViewArray[i]).setHeight(180);
                ((TextView) textViewArray[i]).setTag(userList.get(i));
                ((TextView) textViewArray[i]).setOnClickListener(new View.OnClickListener() {
                    @SuppressLint("HandlerLeak")
                    @Override
                    public void onClick(View view) {
                        User user = (User) view.getTag();
                        Toast.makeText(getActivity(), user.toString(), Toast.LENGTH_SHORT).show();
                        UserEditorFragment userEditorFragment =UserEditorFragment.newInstance();
                        userEditorFragment.setUser(user);


                        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                        fragmentTransaction.hide(myFragmentList);
                        fragmentTransaction.hide(myButtonList);
                        fragmentTransaction.add(R.id.fragment_home_page_LinearLayout01,userEditorFragment);
                        fragmentTransaction.show(userEditorFragment);
                        fragmentTransaction.addToBackStack(null);

                        fragmentTransaction.commit();
                    }
                });
            }

            myFragmentList = new MyFragmentList();
            myButtonList = new MyButtonList();
            // 实例化数据源
//            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getActivity(), R.layout.support_simple_spinner_dropdown_item, userArray);
            ListAdapter listAdapter = new ListAdapter() {
                @Override
                public boolean areAllItemsEnabled() {
                    return false;
                }

                @Override
                public boolean isEnabled(int i) {
                    return false;
                }

                @Override
                public void registerDataSetObserver(DataSetObserver dataSetObserver) {

                }

                @Override
                public void unregisterDataSetObserver(DataSetObserver dataSetObserver) {

                }

                @Override
                public int getCount() {
                    return textViewArray.length;
                }

                @Override
                public Object getItem(int i) {
                    return textViewArray[i];
                }

                @Override
                public long getItemId(int i) {
                    return userList.get(i).getId();
                }

                @Override
                public boolean hasStableIds() {
                    return false;
                }

                @Override
                public View getView(int i, View view, ViewGroup viewGroup) {
                    return textViewArray[i];
                }

                @Override
                public int getItemViewType(int i) {
                    return 1;
                }

                @Override
                public int getViewTypeCount() {
                    return textViewArray.length;
                }

                @Override
                public boolean isEmpty() {
                    return false;
                }
            };
            myFragmentList.setListAdapter(listAdapter);
            // 把这个 MyFragmentList 嵌入到 对应的 布布局中
            fragmentManager.beginTransaction().replace(R.id.fragment_home_page_LinearLayout01, myFragmentList, "myFragmentList").commit();
            fragmentManager.beginTransaction().replace(R.id.fragment_home_page_LinearLayout02, myButtonList, "myButtonList").commit();
        }
    };


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        fragmentManager = getFragmentManager();
        return inflater.inflate(R.layout.fragment_home_page, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    /*    firstButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                findUserListByPage("1", "10");
                getPageVO().setPageIndex(1);
            }
        });
        gobackButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (getPageVO().getPageIndex() == 1) {
                    Toast.makeText(getActivity(), "已经是第一页了", Toast.LENGTH_SHORT).show();
                    return;
                }
                getPageVO().setPageIndex(getPageVO().getPageIndex() - 1);
                findUserListByPage(String.valueOf(getPageVO().getPageIndex()), "10");
            }
        });
        nextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (getPageVO().getPageIndex() == getPageVO().getEndPage()) {
                    Toast.makeText(getActivity(), "已经是最后一页了", Toast.LENGTH_SHORT).show();
                    return;
                }
                getPageVO().setPageIndex(getPageVO().getPageIndex() + 1);
                findUserListByPage(String.valueOf(getPageVO().getPageIndex()), "10");
            }
        });
        endPageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getPageVO().setPageIndex(getPageVO().getEndPage());
                findUserListByPage(String.valueOf(getPageVO().getPageIndex()), "10");
            }
        });*/
        findUserListByPage("1", "10");
    }

    public static class MyFragmentList extends ListFragment {

    }

    public static class MyButtonList extends Fragment {

        LinearLayout linearLayout;

        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View view = inflater.inflate(R.layout.fragment_home_page, null);
            linearLayout = view.findViewById(R.id.fragment_home_page_LinearLayout02);
            Button firstButton = new Button(getActivity());
            Button gobackButton = new Button(getActivity());
            Button nextButton = new Button(getActivity());
            Button endPageButton = new Button(getActivity());
            firstButton.setText("首页");
            gobackButton.setText("上一页");
            nextButton.setText("下一页");
            endPageButton.setText("尾页");
            linearLayout.addView(firstButton);
            linearLayout.addView(gobackButton);
            linearLayout.addView(nextButton);
            linearLayout.addView(endPageButton);
            firstButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    HomePageFragment.getHomePageFragmentInstance().findUserListByPage("1", "10");
                    HomePageFragment.getHomePageFragmentInstance().getPageVO().setPageIndex(1);
                }
            });
            gobackButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (HomePageFragment.getHomePageFragmentInstance().getPageVO().getPageIndex() == 1) {
                        Toast.makeText(getActivity(), "已经是第一页了", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    HomePageFragment.getHomePageFragmentInstance().getPageVO().setPageIndex(HomePageFragment.getHomePageFragmentInstance().getPageVO().getPageIndex() - 1);
                    HomePageFragment.getHomePageFragmentInstance().findUserListByPage(String.valueOf(HomePageFragment.getHomePageFragmentInstance().getPageVO().getPageIndex()), "10");
                }
            });
            nextButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (HomePageFragment.getHomePageFragmentInstance().getPageVO().getPageIndex() == HomePageFragment.getHomePageFragmentInstance().getPageVO().getEndPage()) {
                        Toast.makeText(getActivity(), "已经是最后一页了", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    HomePageFragment.getHomePageFragmentInstance().getPageVO().setPageIndex(HomePageFragment.getHomePageFragmentInstance().getPageVO().getPageIndex() + 1);
                    HomePageFragment.getHomePageFragmentInstance().findUserListByPage(String.valueOf(HomePageFragment.getHomePageFragmentInstance().getPageVO().getPageIndex()), "10");
                }
            });
            endPageButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    HomePageFragment.getHomePageFragmentInstance().getPageVO().setPageIndex(HomePageFragment.getHomePageFragmentInstance().getPageVO().getEndPage());
                    HomePageFragment.getHomePageFragmentInstance().findUserListByPage(String.valueOf(HomePageFragment.getHomePageFragmentInstance().getPageVO().getPageIndex()), "10");
                }
            });
            return view;
        }
    }

    public void findUserListByPage(String pageindex, String pagecount) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("pageindex", pageindex);
        hashMap.put("pagecount", pagecount);
        try {
            String url = HttpUtil.getURLWithParams(originAddress, hashMap);
            HttpUtil.sendHttpRequest(url, new HttpCallbackListener() {
                @Override
                public void onFinish(String response) {
                    Message message = new Message();
                    message.obj = response;
                    handler.sendMessage(message);
                }

                @Override
                public void onError(Exception e) {
                    Toast.makeText(getActivity(), e.getMessage().toString(), Toast.LENGTH_SHORT).show();
                }
            });
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }


    public PageVO getPageVO() {
        return pageVO;
    }

    public void setPageVO(PageVO pageVO) {
        this.pageVO = pageVO;
    }
}